﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SPMS.Log.Core;
using SPMS.Log.Appender;
using System.Threading;

namespace SPMS.Log.Utility
{
    /// <summary>
    /// 通用日志工厂适配器
    /// </summary>
    /// <remarks>用于将日志框架与通用日志框架进行适配</remarks>
    /// <history>
    /// [zanezeng]               2009/9/30 15:50    创建
    /// </history>
    public sealed class CommonLogFactoryAdapter : Commons.Logging.ILogFactory
    {
        #region ---SPMS.Commons.Logging.ILogFactory

        /// <summary>
        /// 获得给定名称的日志对象
        /// </summary>
        /// <param name="logName">要获得的日志对象的名称</param>
        /// <returns>获得的给定名称的日志对象</returns>
        /// <remarks></remarks>
        /// <history>
        /// [zanezeng]               2009/9/22 13:40    创建
        /// </history>
        /// <remarks></remarks>
        /// <history>
        /// [zanezeng]               2009/9/30 15:52    创建
        /// </history>
        public SPMS.Commons.Logging.ILog GetLog( string logName )
        {
            //判断日志对象名称是否为空引用
            if (null == logName)
            {
                //如果日志对象名称为空引用，则默认为空字符串
                logName = string.Empty;
            }

            //用于保存日志对象
            Commons.Logging.ILog commonlog = null;

            //尝试获得给定的日志对象
            if (this.m_Logs.TryGetValue( logName, out commonlog ))
            {
                //返回获得的日志对象
                return commonlog;
            }

            try
            {
                //获得日志对象
                ILog log = LogManager.GetLogger( logName );

                //包装日志
                commonlog = new CommonLogAdapter( log.Logger );

                //记录日志对象
                this.m_Logs.Add( logName, commonlog );

                //返回日志对象
                return commonlog;
            }
            catch
            {
                //如果发生异常，则返回哑元日志对象
                return this.m_DumbLog;
            }
        }

        #endregion

        #region ---Field

        /// <summary>
        /// 哑元日志对象
        /// </summary>
        private SPMS.Commons.Logging.DumbLog m_DumbLog = new SPMS.Commons.Logging.DumbLog();

        /// <summary>
        /// 通用日志对象
        /// </summary>
        private SynchronizedDictionary<string, Commons.Logging.ILog> m_Logs = new SynchronizedDictionary<string, SPMS.Commons.Logging.ILog>( StringComparer.InvariantCultureIgnoreCase );

        #endregion
    }
}
